<template>
  <div class="xiafa_sp" ref="userInfo">
    <el-dialog title="新建下发" class="noselect"
               v-dialogdrag=" { target:'.el-dialog__header',container:'.el-dialog',border:'.el-dialog__wrapper'}"
               :close-on-click-modal="false" :visible.sync="showDialog" :before-close="handleClose">
      <div style="margin: 20px;"></div>
      <el-form :model="modelForm" ref="modelForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label=" " prop="name" :rules="[{ required: true, message: '请输入下发名称', trigger: 'blur' }]">
          <el-input placeholder="请输入下发名称" v-model="modelForm.name" auto-complete="off" :maxlength="20" size="medium" >
            <template slot="prepend">
              <el-tooltip placement="top" content="请输入下发商品库名称">
                <el-button tabIndex="-1">下发商品库名称</el-button>
              </el-tooltip>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label=" " prop="" :rules="[ { required: true, message: '请选择所属区域', trigger: 'change' }]" style="position:relative">
          <div class="el-input el-input-group el-input-group--prepend el-input--medium" >
            <div class="el-input-group__prepend" tabindex="-1">适用门店</div>
            <el-input placeholder="请选择" v-model="districtName" auto-complete="off" :maxlength="5" size="medium" >
              <el-button slot="append" icon="el-icon-caret-bottom" @click="goChose()"></el-button>
            </el-input>
          </div>
          <!--style="position: absolute;z-index:999999;background-color: #fff;width:100%;max-height: 30vh;overflow-y: auto;"-->
          <div  v-if="isDistricts"  class="branch_tree">
            <div style="text-align:left">
              <el-tree
                id="myPanel"
                class="branch_tree_container"
                :data="treeData"
                show-checkbox
                node-key="value"
                ref="tree"
                :default-checked-keys="checkedKey"
                default-expand-all
                :props="defaultProps"@check="getCurrent">
              </el-tree>
            </div>
          </div>
        </el-form-item>

        <!--原料下发 start-->
        <div v-if="tagType==0" >
          <el-form-item label=" " prop="menuId" :rules="[{ required: true, message: '请选择下发商品库', trigger: 'change' }]">
            <div class="el-input el-input-group el-input-group--prepend">
              <el-tooltip style="border-right:0px solid #c0c0c0" placement="top" content="（选择下发商品库）">
                <div class="el-input-group__prepend">下发商品库</div>
              </el-tooltip>
              <el-select v-model="modelForm.storeId" filterable placeholder="请选择下发商品库" size="medium" class="w-100p" @change="getAllDishes();">
                <el-option
                  v-for="item in storeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
          </el-form-item>
        </div>
        <!--原料下发 end-->

        <!--商品下发 start-->
        <div v-if="tagType==1" style="margin-left: 100px;">
          <div class="text-left" style="margin-bottom: 4px;">选择商品库商品<span style="color:red;font-size: 12px;">  （只可选择一个商品库）</span></div>
          <el-row class="text-left" :gutter="15" style="margin-bottom: 20px;">
            <el-col :span="7">
              <div style="border:1px solid #ccc;height: 25vh;overflow-y: auto;"><div style="padding: 5px;color:#888;margin-bottom: 5px;">选择商品库</div>
                <ul class="cate" style="list-style: none;margin:0px;padding:0px;
              line-height: 10px;">
                  <li v-for="(item,index) in storeList" @click="selectDishes(item)" style="padding:10px;border:1px solid #ccc;text-align: left;border-left:0px;border-right:0px;"
                      v-bind:class="{'activity':item.isSelect}"><span>{{item.name}}</span>
                  </li>
                </ul>
              </div>
            </el-col>
            <el-col :span="15" style="padding-right: 47px">
              <div style="padding-left: 10px;height: 24vh;overflow-y: auto;border:1px solid #ccc;padding:5px 10px;">
                <div style="color:#888">包含的商品</div>
                <div v-for="i in dishesList" v-if="dishesList.length>0">
                  <div style="border-bottom: 1px solid #f2f2f2;padding-bottom:10px;font-size: 16px;">  <el-checkbox :indeterminate="i.isIndeterminate" v-model="i.checkAll" @change="handleCheckAllChange(i)">{{i.name}}</el-checkbox></div>
                  <el-checkbox-group  v-model="i.checkboxGroup1" class="text-left" style="padding-top: 10px;margin-bottom: 10px;" @change="handleCheckedCitiesChange(i,i.dishess)">
                    <el-checkbox v-for="(j,index) in i.dishess"  :label="j.id" :key="j.id" style="padding-bottom: 4px;padding-top:2px;width:50%;text-align: left;margin:0px;">{{j.name}}<div style="clear: both"></div></el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
        <!--商品下发 end-->

        <!--成本卡下发 start-->
        <div v-if="tagType==2" style="margin-left: 100px;">
          <div class="text-left" style="margin-bottom: 4px;">选择商品库商品<span style="color:red;font-size: 12px;">  （只可选择一个商品库）</span></div>
          <el-row class="text-left" :gutter="15" style="margin-bottom: 20px;">
            <el-col :span="7">
              <div style="border:1px solid #ccc;height: 25vh;overflow-y: auto;"><div style="padding: 5px;color:#888;margin-bottom: 5px;">选择商品库</div>
                <ul class="cate" style="list-style: none;margin:0px;padding:0px;
              line-height: 10px;">
                  <li v-for="(item,index) in storeList" @click="selectDishes(item)" style="padding:10px;border:1px solid #ccc;text-align: left;border-left:0px;border-right:0px;"
                      v-bind:class="{'activity':item.isSelect}"><span>{{item.name}}</span>
                  </li>
                </ul>
              </div>
            </el-col>
            <el-col :span="15" style="padding-right: 47px">
              <div style="padding-left: 10px;height: 24vh;overflow-y: auto;border:1px solid #ccc;padding:5px 10px;">
                <div style="color:#888">包含的商品</div>
                <div v-for="i in dishesList" v-if="dishesList.length>0">
                  <div style="border-bottom: 1px solid #f2f2f2;padding-bottom:10px;font-size: 16px;">  <el-checkbox :indeterminate="i.isIndeterminate" v-model="i.checkAll" @change="handleCheckAllChange(i)">{{i.name}}</el-checkbox></div>
                  <el-checkbox-group  v-model="i.checkboxGroup1" class="text-left" style="padding-top: 10px;margin-bottom: 10px;" @change="handleCheckedCitiesChange(i,i.dishess)">
                    <el-checkbox v-for="(j,index) in i.dishess"  :label="j.id" :key="j.id" style="padding-bottom: 4px;padding-top:2px;width:50%;text-align: left;margin:0px;">{{j.name}}<div style="clear: both"></div></el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
        <!--成本卡下发 end-->

        <el-form-item label=" " prop="effectiveTime" :rules="[{ required: true, message: '请输入生效日期', trigger: 'blur' }]">
          <div class="el-input el-input-group el-input-group--prepend">
            <div class="el-input-group__prepend">生效日期</div>
            <el-date-picker size="medium"
                            v-model="modelForm.effectiveTime"
                            type="date"
                            format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd"
                            placeholder="选择生效日期"
                            style="width:100%;"
                            :picker-options="pickerOptions0"
            >
            </el-date-picker>
          </div>
        </el-form-item>

        <div class="c-1 text-left" style="margin: 0 91px;">
          1.第一次下发菜品库和更换菜品库，将会清除下发的单店菜品信息。<br />
          2.下发时只下发本次勾选的菜品，未勾选的菜品将会在单店系统中清除。
        </div>

      </el-form>

      <div class="foot-bar-button">
        <el-button :disabled="canSave" type="primary" size="medium" @click="submitForm('modelForm')">
          <span v-if="canSave"><i class="el-icon-loading"></i>提交中</span>
          <span v-else>提交</span>
        </el-button>
        <!--<el-button type="primary" @click="submitForm('modelForm')" size="medium">提交</el-button>-->
        <el-button @click="resetForm('modelForm')" size="medium">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  //注意路径
  export default {
    props: ['isShow', 'id','tagType'],  //参数
    data() {
      return {
        canSave:false,
        modelForm: {},
        selectDistrict:[],
        showDialog: false,
        activityId: "",
        isSave: true,
        downCategeryId: [],
        isUpdate: false,
        treeData:[],
        storeId:window.localStorage.getItem("dishKuId"),
        isDistricts:false,
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        districtId:[],
        districtName:"",
        storeList:[],
        currentStoreId:"",
        dishesList:[],
        checkboxGroup1:[],
        checked:"",
        checkAll: false,
        checkedCities: [],
        isIndeterminate: true,
        selectAllDishes:[],
        checkedKey:[],
        pickerOptions0: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;//如果没有后面的-8.64e7就是不可以选择今天的
          }
        },
        editStoreId:"",
        editDishes:[]
      };
    },
    mounted(){
      let _this=this;
      document.addEventListener("click",function(event){
        var sp = document.getElementById("myPanel");
        if(sp){
          if(!sp.contains(event.target)){            //这句是说如果我们点击到了id为myPanel以外的区域
            _this.isDistricts=false;
          }
        }
      })
    },
    watch: {
      isShow: function (newValue, oldValue) {
        this.showDialog = newValue;
        this.districtName = '';
        this.checkedKey=[];
        this.canSave=false;
        if (newValue) {
          if (this.id != '') {
            this.activityId = this.id;
            this.isSave = false;
            this.isUpdate = true;
            this.$axios.get("dishes/dishesMenus/" + this.activityId + "/update").then(data => {
              this.modelForm = data.content.dishesMenu;
              var tree = data.content.districts;
              this.newLabel(tree);
              this.treeData = tree;
              var branchs=[];
              for(var i=0;i<data.content.branchs.length;i++){
                branchs.push(data.content.branchs[i].branchId);
              }
              this.selectDistrict=[];
              this.districtId=[];
              for(let i=0;i<data.content.branchs.length;i++){
                  this.selectDistrict.push({name:data.content.branchs[i].label,id:data.content.branchs[i].branchId,districtId:data.content.branchs[i].districtId});
                  this.districtId.push(data.content.branchs[i].branchId);
              }
              this.districtName="";
              if(this.selectDistrict.length>0){
                for(var j=0;j< this.selectDistrict.length;j++){
                  this.districtName +=this.selectDistrict[j].name+",";
                }
              }
              var ids=[];
              for(var i=0;i<this.selectDistrict.length;i++){
                // ids.push(this.selectDistrict[i].districtId);
                ids.push(this.selectDistrict[i].id+"_b");
              }
              this.checkedKey=ids;
              this.editDishes=data.content.dishess;

              this.editStoreId=this.modelForm.storeId;
              for(var i=0;i<data.content.storeList.length;i++){
                data.content.storeList[i].isSelect=false;
                if(this.modelForm.storeId== data.content.storeList[i].id){
                  data.content.storeList[i].isSelect=true;
                  this.getDishesList(this.modelForm.storeId,this.isUpdate,this.editDishes);
                }
                // continue;
              }
              this.storeList=data.content.storeList;
            });
          } else {
            this.isSave = true;
            this.isUpdate=false;
            this.$axios.get("dishes/dishesMenus/create").then(data => {
              data.content.dishesMenu.effectiveTime=this.moment().format("YYYY-MM-DD");
              this.modelForm = data.content.dishesMenu;
              var tree = data.content.districts;
              this.newLabel(tree);
              this.treeData = tree;
              for(var i=0;i<data.content.storeList.length;i++){
                data.content.storeList[i].isSelect=false;
              }
              if( data.content.storeList.length>0){
                data.content.storeList[0].isSelect=true;
                this.getDishesList(data.content.storeList[0].id);
                this.modelForm.storeId=data.content.storeList[0].id;
              }
              console.log(data.content.storeList);
              this.storeList=data.content.storeList;
            });
          }
        }
      }
    },
    created() {
      window.this = this;

    },
    methods: {
      goChose(){
        this.isDistricts=!this.isDistricts;
        console.log(this.isUpdate);
        // if(this.isUpdate){
        //
        //   console.log(this.checkedKey);
        // }
      },
      handleCheckAllChange(val) {
        var ids = [];
        if (val) {
          for (var i = 0; i <val.dishess.length; i++) {
            ids.push(val.dishess[i].id);
          }
        }
        val.checkboxGroup1 = val.checkAll ? ids : [];
        val.isIndeterminate = false;
      },
      handleCheckedCitiesChange(all,item) {
        let checkedCount = all.checkboxGroup1.length;
        all.checkAll = checkedCount === item.length;
        all.isIndeterminate = checkedCount > 0 && checkedCount < item.length;
      },
      getDishesList(id,flag,dishess){
        this.$axios.get("dishes/dishesStores/getDishes?storeId="+id).then(res=>{
            if(res.success){
              for(var i=0;i<res.content.length;i++){
                res.content[i].checkAll=false;
                res.content[i].checkboxGroup1=[];
                res.content[i].isIndeterminate=false;
              }
              this.dishesList=res.content;
              if(flag==true){   //数据还原
                if(id==this.editStoreId){
                  for(var j=0;j<dishess.length;j++){
                    for(var i=0;i<this.dishesList.length;i++){
                      for(var n=0;n<this.dishesList[i].dishess.length;n++){
                        if(dishess[j].dishesId==this.dishesList[i].dishess[n].id){
                          this.dishesList[i].checkboxGroup1.push(dishess[j].dishesId);
                        }
                        let checkedCount = this.dishesList[i].checkboxGroup1.length;
                        this.dishesList[i].checkAll = checkedCount === dishess.length;
                        this.dishesList[i].isIndeterminate = checkedCount > 0 && checkedCount < dishess.length;
                      }
                    }
                  }
                }
              }
            }
        },res=>{})
      },
      selectDishes(item){
        for(var i=0;i<this.storeList.length;i++){
          this.storeList[i].isSelect=false;

        }
        item.isSelect=true;
        this.modelForm.storeId=item.id;
        console.log( this.modelForm.storeId);

        this.getDishesList(item.id,this.isUpdate,this.editDishes);
      },
      getCurrent(){
        this.selectDistrict=[];
        this.districtId=[];
        this.checkedKey=[];
        var getCheck=this.$refs.tree.getCheckedNodes();
        for(let i=0;i<getCheck.length;i++){
            if(getCheck[i].iBranch==true){
              this.selectDistrict.push({name:getCheck[i].name,id:getCheck[i].id});
              this.districtId.push(getCheck[i].id);
            }
        }
        this.districtName="";
        if(this.selectDistrict.length>0){
          for(var j=0;j< this.selectDistrict.length;j++){
            this.districtName +=this.selectDistrict[j].name+",";
            this.checkedKey.push(this.selectDistrict[j].id+"_b")
          }
        }

      },
      relation(newList){
      },
      newLabel(newList) {
        if (newList) {
          for (var i = 0; i < newList.length; i++) {
            console.log(newList[i].iBranch);
            if(newList[i].iBranch){
              newList[i].value = newList[i].id + "_b";
            }else {
              newList[i].value = newList[i].id + "";
            }
            newList[i].label = newList[i].name;
            if (!newList[i].children || newList[i].children.length == 0) {
              newList[i].children = null;
            } else {
              for (var s = 0; s < newList[i].children.length; s++) {
                if(newList[i].iBranch){
                  newList[i].children[s].value = newList[i].children[s].id + "_b";
                }else {
                  newList[i].children[s].value = newList[i].children[s].id + "";
                }
                newList[i].children[s].label = newList[i].children[s].name;
                this.newLabel(newList[i].children[s].children);
              }
            }
          }
        }
      },
      goBack() {
        this.router.go(-1);
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {

            var data={};
            console.log(this.modelForm);
            data.dishesMenus=this.modelForm;
            data.branchs=JSON.stringify(this.districtId);
            var selectAllDishes=[];
            for(var i=0;i<this.dishesList.length;i++){
                for(var j=0;j<this.dishesList[i].checkboxGroup1.length;j++){
                  selectAllDishes.push(this.dishesList[i].checkboxGroup1[j]);
                }
            }
            if(selectAllDishes.length<=0){
              this.$message.error("请至少选择一种菜品");
              return;
            }
            if(this.canSave){
              return;
            }
            this.canSave=true;
            data.dishes=JSON.stringify(selectAllDishes);
            if (this.isSave) {
              this.$axios.post("dishes/dishesMenus/create",data,"json").then(data => {
                this.canSave=false;
                if (data.status == 200) {
                  this.$message({
                    message: data.message,
                    type: 'success'
                  });
                  this.$emit('addSuccess');
                } else {
                  this.$message.error(data.message);
                }

              })

            } else {
              this.modelForm._method = "PUT";
              this.$axios.put("dishes/dishesMenus/" + this.activityId + "/update", data,"json").then(data => {
                this.canSave=false;
                if (data.status == 200) {
                  this.$message({
                    message: data.message,
                    type: 'success'
                  });
                  this.$emit('addSuccess');
                } else {
                  this.$message.error(data.message);
                }
              })
            }
          } else {
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$emit('close');
        this.showDialog = false;
      },
      handleClose(done) {
        this.$emit('close');
        done();
      },
      isNum(item, key) {
        var r = /^\+?[1-9][0-9]*$/;
        if (!r.test(item[key])) {
          item[key] = "0.00"
        } else {
          item[key] = item[key]
        }
      },
      isDouble(item, key) {
        var isNum = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
        if (!isNum.test(item[key])) {
          item[key] = "0.00"
        } else {
          item[key] = item[key]
        }
      }
    }
  }
</script>
<style scoped>

  .cate {
    /*height: 100%;*/
  }

  .cate li {
    padding: 8px 0px;
    cursor: pointer;
  }

  .cate .activity {
    color: #fff !important;
    background-color: #428bca !important;
    border:1px solid #428bca !important;
  }

</style>
